<?php
namespace App\Api\Controllers\Agent;


use App\Api\Controllers\BaseController;
use App\Models\AlipayAppOauthUsers;
use App\Models\HStore;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\MyBankStore;
use App\Models\MyBankStoreTem;
use App\Models\NewLandStore;
use App\Models\Order;
use App\Models\Store;
use App\Models\StoreMonthOrder;
use App\Models\StorePayWay;
use App\Models\TfStore;
use App\Models\User;
use App\Models\VbillStore;
use App\Models\WeixinStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Mybank\Mybank;

class SelectController extends BaseController
{

    public function s_code_url(Request $request)
    {
        $message = '暂时无法添加,请使用其他方式';
        return view('errors.page_errors', compact('message'));

    }


    public function sub_code_url(Request $request)
    {
        $message = '暂时无法添加,请使用其他方式';
        return view('errors.page_errors', compact('message'));

    }


    //门店交易统计（交易榜）
    public function ranking(Request $request)
    {
        try {
            $user = $this->parseToken(); //用户信息
            $user_id = $request->get('user_id', '');
            $type = $request->get('type', '1'); //排序：1-交易笔数,由大到小;2-交易笔数由小到大;3-交易金额由大到小;4-交易金额由小到大
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');

            //限制时间
            if (empty($time_end)) {
                $time_end = date('Y-m-d H:i:s', time());
            } else {
                if ($time_start != $time_end) {
                    $date = ((strtotime($time_end) > strtotime($time_start)))?true:false;
                    if (!$date) {
                        $this->status = '2';
                        $this->message = '开始时间不能超过结束时间';
                        return $this->format();
                    }
                }
                $time_end = "$time_end 23:59:59";
            }
            $time_start = "$time_start 00:00:00";

            $user_ids = [];
            if ($user_id) {
                $user_ids = [
                    ['user_id' => $user_id]
                ];
                $user_ids = $this->getSubIds($user_id);
            } else {
                $user_ids = $this->getSubIds($user->user_id);
            }

            if ($type == "1" || $type == "2") {
                $sort = 'desc';
                if ($type == "2") {
                    $sort = 'asc';
                }
                $order_field = "COUNT(`total_amount`)";
            } else {
                $sort = 'desc';
                if ($type == "4") {
                    $sort = 'asc';
                }

                $order_field = "SUM(`total_amount`)";
            }

            $obj = Order::query()->select([
                'store_id',
                'store_name',
                DB::raw("SUM(`total_amount`) AS `total_amount`, COUNT(`total_amount`) AS `total_count`"),
                DB::raw("SUM(IF(`ways_source`='alipay', `total_amount`, 0)) AS `alipay_amount`"),
                DB::raw("COUNT(IF(`ways_source`='alipay', true, null)) AS `alipay_count`"),
                DB::raw("SUM(IF(`ways_source`='weixin', `total_amount`, 0)) AS `weixin_amount`"),
                DB::raw("COUNT(IF(`ways_source`='weixin', true, null)) AS `weixin_count`"),
                DB::raw("COUNT(IF(`pay_method`='alipay_face', true, null)) as `alipay_face_count`"),
                DB::raw("COUNT(IF(`pay_method`='weixin_face', true, null)) as `weixin_face_count`")
            ])
                ->whereIn('user_id', $user_ids)
                ->whereIn('pay_status', [1, 3, 4])
                ->where('created_at', '>=', $time_start)
                ->where('created_at', '<=', $time_end)
                ->groupBy('store_id')
                ->orderBy(DB::raw($order_field), $sort);

            $this->t = $obj->paginate(10)->total();
            $data = $this->page($obj)->get();
        } catch (\Exception $exception) {
            $this->status = '2';
            $this->message = $exception->getMessage();
            return $this->format();
        }

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($data);
    }

//    public function ranking(Request $request)
//    {
//
//        try {
//            $user = $this->parseToken();//
//            $type = $request->get('type', '1');//1 交易笔数 由大到小
//            $month = $request->get('month', '');
//
//
//            if (env('DB_D1_HOST')) {
//                $obj = DB::connection("mysql_d1")->table("stores");
//            } else {
//                $obj = DB::table('stores');
//            }
//
//            //1 交易笔数
//            if ($type == "1" || $type == "2") {
//                $sort = 'desc';
//                if ($type == "2") {
//                    $sort = 'asc';
//                }
//
//                $obj = $obj->join('store_month_counts', 'stores.store_id', 'store_month_counts.store_id')
//                    ->where('store_month_counts.month', $month)
//                    ->orderBy('store_month_counts.total_count', $sort)
//                    ->select('store_month_counts.*', 'stores.store_name');
//            } else {
//                $sort = 'desc';
//                if ($type == "4") {
//                    $sort = 'asc';
//                }
//                $obj = $obj->join('store_month_counts', 'stores.store_id', 'store_month_counts.store_id')
//                    ->where('store_month_counts.month', $month)
//                    ->orderBy('store_month_counts.total_amount', $sort)
//                    ->select('store_month_counts.*', 'stores.store_name');
//
//            }
//
//
//            $this->t = $obj->count();
//            $data = $this->page($obj)->get();
//            $this->status = 1;
//            $this->message = '数据返回成功';
//            return $this->format($data);
//
//
//        } catch (\Exception $exception) {
//            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
//        }
//
//    }


    //打款查询
    public function dk_select(Request $request)
    {

        try {
            $user = $this->parseToken();//
            $store_id = $request->get('store_id', '');//1 交易笔数 由大到小
            $time = $request->get('time', '');
            $company = $request->get('company', '');

            $check_data = [
                'company' => '通道类型',
                'time' => '打款时间',
                'store_id' => '门店ID',

            ];

            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $store = Store::where('store_id', $store_id)
                ->select('store_name')
                ->first();
            if (!$store) {
                return json_encode(['status' => 2, 'message' => '门店ID不存在']);

            }
            $store_name = $store->store_name;

            return json_encode([
                'status' => 1,
                'message' => '查询成功',
                'data' => [
                    'store_name' => $store_name,
                    'time' => $time,
                    'total_amount' => '0.01',
                    'dk_time' => $time,
                    'dk_desc' => '打款成功',

                ]
            ]);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }

    }


    //代理商上级查询
    public function select_pid_user(Request $request)
    {
        try {
            $user_name = $request->get('user_name', '');
            $user = User::orWhere('name', $user_name)
                ->orWhere('phone', $user_name)
                ->select('level', 'id', 'name', 'phone', 'pid')
                ->first();

            if (!$user) {
                return json_encode([
                    'status' => 2,
                    'message' => '用户不存在',

                ]);
            }
            $pid = $user->pid;
            $user_name = $user->name . '(' . $user->phone . ')';
            for ($i = 0; $i < $user->level + 2; $i++) {
                if ($pid == 0) {
                    break;
                }
                $user = User::where('id', $pid)
                    ->select('level', 'id', 'name', 'phone', 'pid')
                    ->first();

                $pid = $user->pid;
                $user_name = $user_name . '=>' . $user->name . '(' . $user->phone . ')';
            }

            return json_encode([
                'status' => 1,
                'message' => '数据返回成功',
                'data' => [
                    'info' => $user_name
                ]
            ]);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),

            ]);

        }
    }


    //清除通道
    public function clear_ways_type(Request $request)
    {
        try {

            $company = $request->get('company', '');
            $store_id = $request->get('store_id', '');
            $user = $this->parseToken();

            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('清除通道');
            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限清除通道']);
            }


            //传化
            if ($company == "tfpay") {
                $TfStore = TfStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }


            //支付宝
            if ($company == "alipay") {
                $AlipayAppOauthUsers = AlipayAppOauthUsers::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //和融通
            if ($company == "herongtong") {
                $TfStore = HStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }


            //新大陆
            if ($company == "newland") {
                $NewLandStore = NewLandStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }

            //新大陆
            if ($company == "mybank") {
                $MyBankStore = MyBankStoreTem::where('OutMerchantId', $store_id)->delete();
                $MyBankStore = MyBankStore::where('OutMerchantId', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }


            //微信官方
            if ($company == "weixin") {
                $NewLandStore = WeixinStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }



            //随行付
            if ($company == "vbill") {
                $NewLandStore = VbillStore::where('store_id', $store_id)->delete();
                $StorePayWay = StorePayWay::where('company', $company)->where('store_id', $store_id)->delete();
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功'
                ]);

            }


            return json_encode([
                'status' => 2,
                'message' => '暂不支持清除通道'
            ]);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),

            ]);

        }
    }


    /**
     * 根据门店ID查看收银员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function merchant_lists(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $name = $request->get('name', '');

            $where = [];


            if ($name) {
                $where[] = ['merchants.name', 'like', '%' . $name . '%'];
            }


            if ($store_id) {
                $where[] = ['stores.store_id', '=', $store_id];
            }


            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("merchant_stores");
            } else {
                $obj = DB::table('merchant_stores');
            }

            $obj->join('merchants', 'merchant_stores.merchant_id', '=', 'merchants.id')
                ->join('stores', 'merchant_stores.store_id', '=', 'stores.store_id')
                ->where($where)
                ->select('stores.store_name', 'merchants.id as merchant_id', 'merchants.name', 'merchants.phone', 'merchants.type', 'merchants.logo', 'merchants.wx_logo');


            $this->t = $obj->count();
            $data = $this->page($obj)->get();

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 添加收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_merchant(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $type = $request->get('type', '2');
            $name = $request->get('name', '');
            $phone = $request->get('phone', '');
            $data = $request->except(['token']);
            $password = $request->get('password', '');
            $stores = Store::where('store_id', $store_id)
                ->first();
            if ($password == "") {
                $password = '000000';
            }
            if ($name == "") {
                $this->status = 2;
                $this->message = '姓名必填';
                return $this->format();
            }

            if ($phone == "") {
                $this->status = 2;
                $this->message = '手机号必填';
                return $this->format();
            }


            if (!$stores) {
                $this->status = 2;
                $this->message = '门店不存在';
                return $this->format();
            }


            $rules = [
                'phone' => 'required|min:11|max:11',
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {
                return json_encode([
                    'status' => 2,
                    'message' => '手机号位数不正确',
                ]);
            }


            //验证密码
            if (strlen($password) < 6) {
                return json_encode([
                    'status' => 2,
                    'message' => '密码长度不符合要求'
                ]);
            }

            $rules = [
                'phone' => 'required|unique:merchants',
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {

                return json_encode([
                    'status' => 2,
                    'message' => '手机号已经注册'
                ]);
            } else {
                $dataIN = [
                    'pid' => $stores->merchant_id ? $stores->merchant_id : "0",
                    'type' => $type,
                    'name' => $name,
                    'email' => '',
                    'password' => bcrypt($password),
                    'phone' => $phone,
                    'user_id' => $stores->user_id,//推广员id
                    'config_id' => $stores->config_id,
                    'wx_openid' => ''
                ];
                $insert = Merchant::create($dataIN);
                $merchant_id = $insert->id;
            }

            MerchantStore::create([
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
            ]);


            $this->status = 1;
            $this->message = '收银员添加成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 绑定收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bind_merchant(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id');
            $type = $request->get('type');
            $merchant_id = $request->get('merchant_id');


            $check_data = [
                'store_id' => '门店ID',
                'type' => '角色类型',
                'merchant_id' => '收银员',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $MerchantStore = MerchantStore::where('store_id', $store_id)
                ->where('merchant_id', $merchant_id)
                ->first();

            if ($MerchantStore) {
                return json_encode([
                    'status' => 2,
                    'message' => '收银员已经绑定无需重复绑定'
                ]);
            }

            MerchantStore::create([
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'type' => $type,
            ]);


            $this->status = 1;
            $this->message = '收银员绑定成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 修改收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function up_merchant(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $request->get('merchant_id');
            $store_id = $request->get('store_id');
            $name = $request->get('name', '');
            $password = $request->get('password', '');
            $data = $request->except(['token', 'merchant_id', 'store_id', 'password']);


            if ($password == "") {
                $password = '000000';
            }
            if ($name == "") {
                $this->status = 2;
                $this->message = '姓名必填';
                return $this->format();
            }


            if ($password && $password != '000000') {
                //验证密码
                if (strlen($password) < 6) {
                    return json_encode([
                        'status' => 2,
                        'message' => '密码长度不符合要求'
                    ]);
                }

                $data['password'] = bcrypt($password);
            }


            $dataIN = $data;

            $Merchant = Merchant::where('id', $merchant_id)->select('phone')
                ->first();

            $phone = $Merchant->phone;
            if ($phone != $data['phone']) {
                $rules = [
                    'phone' => 'required|unique:merchants',
                ];
                $validator = Validator::make($data, $rules);
                if ($validator->fails()) {

                    return json_encode([
                        'status' => 2,
                        'message' => '手机号已经注册'
                    ]);
                }
            }


            Merchant::where('id', $merchant_id)->update($dataIN);

            $this->status = 1;
            $this->message = '收银员修改成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 删除收银员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */

    public function del_merchant(Request $request)
    {
        try {
            $user = $this->parseToken();
            $merchant_id = $request->get('merchant_id', '');
            $store_id = $request->get('store_id', '');

            $check_data = [
                'merchant_id' => '收银员',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            $user = User::where('id', $user->user_id)->first();
            $hasPermission = $user->hasPermissionTo('删除收银员');

            if (!$hasPermission) {
                return json_encode(['status' => 2, 'message' => '没有权限']);
            }


            if ($merchant_id == "") {
                $this->status = 2;
                $this->message = '请选择收银员';
                return $this->format();
            }
            $Merchant = Merchant::where('id', $merchant_id)->first();

            if (!$Merchant) {
                $this->status = 2;
                $this->message = '收银员不存在';
                return $this->format();
            }

            if ($store_id) {
                //删除收银员关联表
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->where('store_id', $store_id)
                    ->delete();
            } else {
                //删除收银员关联表
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->delete();
            }

            $Merchant->delete();


            $this->status = 1;
            $this->message = '收银员删除成功';
            return $this->format();


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


    /**
     * 单个收银员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function merchant_info(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $request->get('merchant_id');
            $store_id = $request->get('store_id', '');

            $check_data = [
                'merchant_id' => '收银员',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            $data = Merchant::where('id', $merchant_id)->first();
            if (!$data) {
                $this->status = 2;
                $this->message = '收银员不存在';
                return $this->format();
            }


            //门店id存在
            if ($store_id) {
                //收银员的收款聚合码
                $data->pay_qr = url('/qr?store_id=' . $store_id . '&merchant_id=' . $merchant_id . '');
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);


        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }

    }


}
